﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Input;

namespace Nx.Commands
{
    public abstract class GlobalCommand<T> : ICommand
    {
        private Command<T> commandImpl;

        public event EventHandler CanExecuteChanged;

        protected GlobalCommand()
        {
            commandImpl = new Command<T>(ExecuteHandler, CanExecuteHandler);
        }

        protected virtual bool CanExecuteHandler(T parameter)
        {
            return true;
        }

        protected abstract void ExecuteHandler(T parameter);

        public bool CanExecute(object parameter)
        {
            return commandImpl.CanExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            commandImpl.Execute((T)parameter);
        }

        [SuppressMessage("Microsoft.Design", "CA1030", Justification = "Must be a method, so view model can optianally force view notification about command availability.")]
        public void RaiseCanExecuteChanged()
        {
            OnCanExecuteChanged();
        }

        private void OnCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}
